import Vue from 'vue'
import Vuex from 'vuex'
import {
   getHouseList,
   deleteItem,
   editItem,
   addItem,
  } from "@/api"

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userInfo: {},
    routerList: [],
    visible: false,
    houseList: [],
    // 分页器的默认值
    pages: {
      size: 10,
      current: 1,
      total: 0
    },
    searchData: {}
  },
  mutations: {
    CHANGE_USER_INFO(state, data) {
      state.userInfo = data
    },
    CHANGE_ROUTER_LIST(state, data) {
      state.routerList = data
    },
    CHANGE_VISIBLE(state, data) {
      state.visible = !state.visible
    },
    CHANGE_HOUSE_LIST(state, data) {
      state.houseList = data
    },
    CHANGE_PAGES(state, data) {
      state.pages = {
        ...data
      }
    },
    CHANGE_SEARCH(state, data) {
        state.searchData = {}
    }
  },
  actions: {
    // 数据持久化：1、本地存储，2、通过服务端保存数据
    // 更改
    // 获取房源列表
    getHouseList(context, data = context.state.pages) {
      getHouseList({...data, ...context.state.searchData}).then(res => {
        // 房源数据
        context.commit('CHANGE_HOUSE_LIST', res.data.list)

        // 修改分页器
        context.commit('CHANGE_PAGES', {
          ...data,
          total: res.data.total
        })
      })
    },
    // 删除
    deleteItem(context, data) {
      deleteItem({id: data}).then(res => {
        //  删除之后在获取houstlist
        context.dispatch('getHouseList')
      })
    },
    // 编辑
    editStoreOk(context, data) {
      editItem(data).then(res => {
        //  修改之后在获取houstlist
        context.dispatch('getHouseList')
      })
    },
    addStoreItem(context, data) {
      addItem(data).then(res => {
        //  添加之后在获取houstlist
        context.dispatch('getHouseList')
      })
    }
  },
  modules: {
  }
})
